import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store/index'

const service = axios.create({
  baseURL: process.env.baseURL,
  timeout: 15000,
  withCredentials: false
})

service.interceptors.request.use((config: any): object => {
  config.headers['X-Requested-With'] = 'axios'
  return config
}, (error: any): object => {
  return Promise.reject(error)
})

service.interceptors.response.use(
  function (response:any) {
    const res = response.data
    const whiteCode = [20000, 200001]
    const message = res.data ? res.data : res.msg
    if (res.code === 40003) {
      MessageBox.alert(message, '系统提示', {
        confirmButtonText: '知道了',
        callback: (action: any) => {
          const d = location.origin ? location.origin : location.protocol + '://' + location.host
          window.location.href = d + res.forword
        }
      })
    } else if (whiteCode.indexOf(res.code) === -1) {
      if (res.code === 40001) {
        MessageBox.confirm('确定登出吗?', '确定登出', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          location.href = res.url
        })
      } else {
        Message({
          message: message,
          type: 'error',
          duration: 5 * 1000
        })
      }
    }
    const codelist = [403, 405, 50008, 50012, 50014, 401]
    if (codelist.indexOf(res.code) !== -1) {
      if (store.state.user.token) {
        MessageBox.confirm('系统检测到您已被登出，点击重新登录进入登录页面', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          location.href = store.state.user.login + location.href
        })
      } else {
        location.href = store.state.user.login + location.href
      }
      return Promise.reject(message)
    } else {
      return Promise.reject(message)
    }
    // return Promise.resolve(res)
  }
)

export default service